package org.zxp.thread.communication.join;

import java.util.Date;

/**
 * @program: zxp-thread-test
 * @description: 通过join实现的控制方法运行时间
 * @author: X-Pacific zhang
 * @create: 2019-01-14 09:51
 **/
public class ControlTime {
    public static void main(String[] args) throws Exception {
        Date d1 = new Date();
        Thread thread = new Thread(() -> new ControlTime().control());
        new ControlTime().monitor(thread,1000);
    }

    /**
     * 控制方法运行时间
     * @param thread
     * @param cTime
     * @throws Exception
     */
    public void monitor(Thread thread,long cTime) throws Exception {
        long begin = System.currentTimeMillis();
        if(thread.getState() != Thread.State.NEW){
            throw new Exception("Thread State Error");
        }
        thread.start();
        thread.join(cTime);
        if(thread.getState() != Thread.State.TERMINATED){
            thread.stop();
        }
        System.out.println("运行时间监控："+(System.currentTimeMillis()-begin));
    }
    /**
     * 这个方法是被控制运行时间方法
     */
    public void control(){
        try {
            Thread.sleep(500);
            System.out.println("正常结束");
//            while(true){
//
//            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //一定要做好释放资源
            System.out.println("释放资源");
        }
    }
}
